﻿#include "PyCodeEditor.h"
#include "PyLexer.h"
#include <QRegularExpression>


PyCodeEditor::PyCodeEditor(QWidget *parent)
    : BaseCodeEditor{parent}
{
    setLexer(new PyLexer(this));
}

QString PyCodeEditor::convertPython2Prints(const QString &input)
{
    QStringList lines = input.split('\n');
    QStringList outLines;

    QRegularExpression indentRe("^(\\s*)"); // 缩进匹配
    QRegularExpression printRe("^print\\s+(.*)$"); // print 内容匹配

    for (QString line : lines) {
        QString original = line;
        QString trimmed = line.trimmed();

        // 忽略空行
        if (trimmed.isEmpty()) {
            outLines << line;
            continue;
        }

        // 非 print 开头的不处理
        if (!trimmed.startsWith("print ") && !trimmed.startsWith("print\t")) {
            outLines << line;
            continue;
        }

        // 提取缩进
        QString indent;
        auto mIndent = indentRe.match(line);
        if (mIndent.hasMatch())
            indent = mIndent.captured(1);

        // 分离注释
        QString codePart = line;
        QString commentPart;
        int commentIndex = line.indexOf('#');
        if (commentIndex >= 0) {
            codePart = line.left(commentIndex);
            commentPart = line.mid(commentIndex);
        }

        QString content = codePart.mid(indent.length()).trimmed();
        if (content.startsWith("print(")) {
            outLines << line; // 已经是 print() 格式
            continue;
        }

        auto m = printRe.match(content);
        if (!m.hasMatch()) {
            outLines << line;
            continue;
        }

        QString inside = m.captured(1).trimmed();

        QString newLine = QString("%1print(%2)").arg(indent, inside);
        if (!commentPart.isEmpty())
            newLine += " " + commentPart;

        outLines << newLine;
    }

    return outLines.join('\n');
}
